import { ecc } from 'eosjs/dist/eosjs-ecc-migration';
import * as bip39 from "bip39";

// 找一个 可用的助记词转私钥包

import * as bitcore from 'bitcore-lib';
import {PublicKey} from "bitcore-lib";
import {Address} from "ethereumjs-util";
import {sha256} from "@/common/util/crypto";
import bs58 from "bs58"; //助记词转成私钥
let pri: any = bitcore.PrivateKey
let hdPri: any = bitcore.HDPrivateKey
let ethAddress= ''
// 查询私钥是否正确
export function isValidPrivate(privateKey: string) {
    return ecc.isValidPrivate(privateKey);
}

// 私钥获取公钥
export function privateToPublic(privateKey: string) {
    // if (isValidPrivate(privateKey) == false) return '';
    // let pub=pri.fromWIF(privateKey).toPublicKey().toString();
    // return "M"+pub.substring(1);
    // if (ecc.isValidPrivate(privateKey) == false) return '';
    const pub =ecc.privateToPublic(privateKey,'MOS')
    return 'M'+pub.substring(1);
}
//助记词获取私钥
export function mnemonicToPrivate(mnemonic: string){
    const seed = bip39.mnemonicToSeedSync(mnemonic, '');
    const hdRoot = hdPri.fromSeed(seed); //根据种子 生成私钥
    const privateKeyHex = Buffer.from(hdRoot.privateKey.toString(), 'hex');

    ethAddress = Address.fromPrivateKey(privateKeyHex).toString();
    // alert("import key3 "+ethAddress);
    let versionedKey = '80' + hdRoot.privateKey.toString();
    const sha256dKey: any = sha256(Buffer.from(versionedKey, 'hex'));
    const checksum = sha256(Buffer.from(sha256dKey, 'hex'))
        .toString()
        .substring(0, 8);
    versionedKey += checksum;
    const privateKey = bs58.encode(new Uint8Array(Buffer.from(versionedKey, 'hex')))
    return privateKey
}
// 获取新私钥公钥助记词

export async function getRandomKeyPair() {
    const mnemonic = bip39.generateMnemonic(); //助记词
    const privateKey = mnemonicToPrivate(mnemonic)
    // const publicKey = pri.fromWIF(privateKey).toPublicKey().toString()
    const publicKey =ecc.privateToPublic(privateKey,'MOS')
    return { mnemonic,privateKey, publicKey };
}

// 查询公钥是否正确
export function isValidPublic(publicKey: string) {
    return ecc.isValidPublic(publicKey);
}

export function signature(data: Buffer | string, privateKey: string, arbitrary: boolean = false, isHash: boolean = false) {
    if (!privateKey) {
        return '';
    }
    let sig: string;
    if (isHash) {
        sig = ecc.signHash(data, privateKey, 'utf8');
    } else {
        sig = ecc.sign(data, privateKey, 'utf8');
    }
    return sig;
}